//
//  AppDelegate.m
//  DayByDay
//
//  Created by dllo on 16/5/13.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "AppDelegate.h"
#import "MainPageViewController.h"
#import "LeftSortsViewController.h"
#import "GuideViewController.h"
//#import "UMSocialWechatHandler.h"
#import "STKAudioPlayerHandle.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MPNowPlayingInfoCenter.h>
#import <MediaPlayer/MPMediaItem.h>
#import <UIImageView+WebCache.h>

@interface AppDelegate ()

@property (nonatomic, strong)NSTimer *timer;
@property (nonatomic, strong)NSMutableDictionary *dic;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    MainPageViewController *mainVC = [[MainPageViewController alloc] init];
    
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:mainVC];
    self.mainNAVC = naVC;
    LeftSortsViewController *leftSortsVC = [[LeftSortsViewController alloc] init];
    self.leftSlideVC = [[LeftSlideViewController alloc] initWithLeftView:leftSortsVC andMainView:naVC];
    self.JHJTabBar = [[JHJTabBarController alloc] init];
    self.JHJTabBar.viewControllers =@[self.leftSlideVC];
    GuideViewController *guideVC = [[GuideViewController alloc] init];
    self.window.rootViewController = guideVC;
    
//    [[UIView appearance] setBackgroundColor:[UIColor yellowColor]];
    
    guideVC.block = ^{
        self.window.rootViewController = self.JHJTabBar;
    };
    AppDelegate *tempApp = self;
    self.leftSlideVC.sliderBlock = ^(BOOL isOpen) {
        if (isOpen) {
            [tempApp.JHJTabBar showTabBarWithAnimation:YES];
        } else {
            [tempApp.JHJTabBar hiddenTabBarWithAnimation:YES];
        }
    };
    
    //直接将UMSocial_Sdk_4.2.1 导入工程就可以了
    //然后按照友盟文档就可以了
//    [UMSocialData setAppKey:@"57516e7667e58e6a2b002c8d"];
    
    // 远程播放;
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    return YES;
}

//- (BOOL)canBecomeFirstResponder
//{
//    return YES;
//}

- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
    NSLog(@"jkdsfjkdsjfdsklf");
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        
        switch (receivedEvent.subtype) {
                
            case UIEventSubtypeRemoteControlTogglePlayPause:
                [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] pauseOrResumePlayer];
                NSLog(@"RemoteControlEvents: pause");
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] nextSonger];
                NSLog(@"RemoteControlEvents: playModeNext");
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] lastSonger];
                NSLog(@"RemoteControlEvents: playPrev");
                break;
            case UIEventSubtypeRemoteControlStop:
                NSLog(@"sklfkjdslfs");
                break;
            case UIEventSubtypeRemoteControlPause:
                NSLog(@"jskdfkdsfsfsd;f;dsfjsdklf");
                [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] pauseOrResumePlayer];
                break;
            case UIEventSubtypeRemoteControlPlay:
                NSLog(@"====dskfsdlfdsf");
                [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] pauseOrResumePlayer];
                break;
            default:
                break;
        }
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [application beginBackgroundTaskWithExpirationHandler:^{
        NSLog(@"========sadfkjsdklfjlks;dfkl;sdfljkdsf----------------------");
        
    }];
    
    NSLog(@"sadfkjsdklfjlks;dfkl;sdfljkdsf----------------------");

    [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] addObserver:self forKeyPath:@"currentOfMusic" options:NSKeyValueChangeNewKey || NSKeyValueChangeOldKey context:nil];
//    if (!self.timer) {
//        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
//    }
    [self setBackgroundinfoWithNum:[STKAudioPlayerHandle shareSTKAudioPlayerHandle].currentOfMusic];
}


- (void)timerAction {
    if (!self.dic) {
        self.dic = [NSMutableDictionary dictionary];
    }
    [self changeProgressWithdic:self.dic];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"currentOfMusic"]) {
        NSLog(@"%@",change);
        NSLog(@"%ld",(unsigned long)[STKAudioPlayerHandle shareSTKAudioPlayerHandle].mutableArray.count);
            [self setBackgroundinfoWithNum:[[change objectForKey:@"new"] integerValue]];
        
    }
}

- (void)setBackgroundinfoWithNum:(NSInteger)num {
    if (num == [STKAudioPlayerHandle shareSTKAudioPlayerHandle].mutableArray.count) {
        num = 0;
    }
    PosterDetailSongsModel *model = [[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] mutableArray] objectAtIndex:num];
    NSMutableDictionary *songInfo = [ [NSMutableDictionary alloc] init];
    
//    UIImageView *imageV = [[UIImageView alloc] init];
    NSLog(@"11111111111111");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.picUrl]]];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"222222222222222");
            MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage:image];
            [songInfo setObject: model.name forKey:MPMediaItemPropertyTitle];
            [songInfo setObject: model.singerName forKey:MPMediaItemPropertyArtist];
            [songInfo setObject: model.name forKey:MPMediaItemPropertyAlbumTitle];
            [songInfo setObject: albumArt forKey:MPMediaItemPropertyArtwork];
            [songInfo setObject:[NSNumber numberWithDouble:[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayer].duration] forKeyedSubscript:MPMediaItemPropertyPlaybackDuration];
            [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
            
        });
        
    });
    

}

- (void)changeProgressWithdic:(NSMutableDictionary *)dict{
    
    
        
        //当前播放时间
        dict = [NSMutableDictionary dictionaryWithDictionary:[[MPNowPlayingInfoCenter defaultCenter] nowPlayingInfo]];
        //歌曲的剩余时间
        [dict setObject:[NSNumber numberWithDouble:[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayer].duration] forKeyedSubscript:MPMediaItemPropertyPlaybackDuration];
        
        [dict setObject:[NSNumber numberWithDouble:[[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayer] progress]] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime]; //音乐当前已经过时间
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    NSLog(@"dskjflksdfkjsd;fsd;f;sdfjsdkfjsdl;afjldsfdskfsk;df+++++++");
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
//    [application endReceivingRemoteControlEvents];
    [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] removeObserver:self forKeyPath:@"currentOfMusic"];
    [application endBackgroundTask:UIBackgroundTaskInvalid];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    NSLog(@"1111");
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
